package com.ztej.query.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.ztej.query.R;
import com.ztej.query.adapter.SimpleTreeAdapter;
import com.ztej.query.adapter.StaffAdapter;
import com.ztej.query.bean.Bean;
import com.ztej.query.bean.FileBean;
import com.ztej.query.bean.Node;
import com.ztej.query.bean.TreeListViewAdapter;
import com.ztej.query.model.Contact;
import com.ztej.query.model.Region;
import com.ztej.query.parser.JsonHelper;
import com.ztej.query.parser.PullContactParser;
import com.ztej.query.utils.Tools;

import org.apache.http.conn.ConnectTimeoutException;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.ContentValues.TAG;

public class TreeActivity extends Activity {

    private Button btnBack, btnSearch, btnBack2;
    private FrameLayout flTitle;
    private LinearLayout llSearch;
    private EditText etSearch;
    private ImageView ivSearch;

    private List<Bean> mDatas = new ArrayList<Bean>();
    private List<FileBean> mDatas2 = new ArrayList<FileBean>();
    private List<FileBean> mDatas3 = new ArrayList<FileBean>();

    private ListView mTree, lvSearch;
    private TreeListViewAdapter mAdapter;

    private StaffAdapter mStaffAdapter;
//    private List<Map<String, String>> listSearch;
    private List<Contact> listSearch;

    private ProgressDialog progressBar;



    Map<String, String> mapRegion = new HashMap<String, String>();
//    List<Map<String, String>> listRegion = new ArrayList<Map<String, String>>();
    List<Region> listRegion = new ArrayList<Region>();
    private static class MyHandler extends Handler {
        private final WeakReference<TreeActivity> mActivity;

        public MyHandler(TreeActivity activity) {
            mActivity = new WeakReference<TreeActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final TreeActivity activity = mActivity.get();
            if (activity != null) {
                // ...
                switch (msg.what){
                    case 0:
                        JsonHelper jsonHelper = new JsonHelper();
                        activity.listRegion = jsonHelper.parseRegion((String)msg.obj);

                        if (activity.listRegion.size()!=0){

                            activity.progressBar.cancel();

                            for (int i = 0; i <activity.listRegion.size() ; i++) {
                                if (activity.listRegion.get(i).getParentid().equals("0")){
                                    activity.mDatas3.add(new FileBean(Integer.parseInt(activity.listRegion.get(i).getFid()),
                                            Integer.parseInt(activity.listRegion.get(i).getParentid()), activity.listRegion.get(i).getName()));
                                }

                                else if (activity.listRegion.get(i).getParentid().equals("1")){
                                    activity.mDatas3.add(new FileBean(Integer.parseInt(activity.listRegion.get(i).getFid()),
                                            Integer.parseInt(activity.listRegion.get(i).getParentid()), activity.listRegion.get(i).getName()));
                                }

                                else if (activity.listRegion.get(i).getParentid().equals("11")){
                                    activity.mDatas3.add(new FileBean(Integer.parseInt(activity.listRegion.get(i).getFid()),
                                            Integer.parseInt(activity.listRegion.get(i).getParentid()), activity.listRegion.get(i).getName()));
                                }

                                else if (activity.listRegion.get(i).getParentid().equals("11035")){
                                    activity.mDatas3.add(new FileBean(Integer.parseInt(activity.listRegion.get(i).getFid()),
                                            Integer.parseInt(activity.listRegion.get(i).getParentid()), activity.listRegion.get(i).getName()));
                                }

                                else if (activity.listRegion.get(i).getParentid().equals("11065")){
                                    activity.mDatas3.add(new FileBean(Integer.parseInt(activity.listRegion.get(i).getFid()),
                                            Integer.parseInt(activity.listRegion.get(i).getParentid()), activity.listRegion.get(i).getName()));
                                }

                                else if (activity.listRegion.get(i).getParentid().equals("11080")){
                                    activity.mDatas3.add(new FileBean(Integer.parseInt(activity.listRegion.get(i).getFid()),
                                            Integer.parseInt(activity.listRegion.get(i).getParentid()), activity.listRegion.get(i).getName()));
                                }

                                else if (activity.listRegion.get(i).getParentid().equals("11105")){
                                    activity.mDatas3.add(new FileBean(Integer.parseInt(activity.listRegion.get(i).getFid()),
                                            Integer.parseInt(activity.listRegion.get(i).getParentid()), activity.listRegion.get(i).getName()));
                                }

                                else if (activity.listRegion.get(i).getParentid().equals("11110")){
                                    activity.mDatas3.add(new FileBean(Integer.parseInt(activity.listRegion.get(i).getFid()),
                                            Integer.parseInt(activity.listRegion.get(i).getParentid()), activity.listRegion.get(i).getName()));
                                }

                                else if (activity.listRegion.get(i).getParentid().equals("11120")){
                                    activity.mDatas3.add(new FileBean(Integer.parseInt(activity.listRegion.get(i).getFid()),
                                            Integer.parseInt(activity.listRegion.get(i).getParentid()), activity.listRegion.get(i).getName()));
                                }

                                else if (activity.listRegion.get(i).getParentid().equals("11150")){
                                    activity.mDatas3.add(new FileBean(Integer.parseInt(activity.listRegion.get(i).getFid()),
                                            Integer.parseInt(activity.listRegion.get(i).getParentid()), activity.listRegion.get(i).getName()));
                                }

                                else if (activity.listRegion.get(i).getParentid().equals("11170")){
                                    activity.mDatas3.add(new FileBean(Integer.parseInt(activity.listRegion.get(i).getFid()),
                                            Integer.parseInt(activity.listRegion.get(i).getParentid()), activity.listRegion.get(i).getName()));
                                }

                                else if (activity.listRegion.get(i).getParentid().equals("11175")){
                                    activity.mDatas3.add(new FileBean(Integer.parseInt(activity.listRegion.get(i).getFid()),
                                            Integer.parseInt(activity.listRegion.get(i).getParentid()), activity.listRegion.get(i).getName()));
                                }

                                else if (activity.listRegion.get(i).getParentid().equals("11180")){
                                    activity.mDatas3.add(new FileBean(Integer.parseInt(activity.listRegion.get(i).getFid()),
                                            Integer.parseInt(activity.listRegion.get(i).getParentid()), activity.listRegion.get(i).getName()));
                                }

                                else if (activity.listRegion.get(i).getParentid().equals("11185")){
                                    activity.mDatas3.add(new FileBean(Integer.parseInt(activity.listRegion.get(i).getFid()),
                                            Integer.parseInt(activity.listRegion.get(i).getParentid()), activity.listRegion.get(i).getName()));
                                }

                                else if (activity.listRegion.get(i).getParentid().equals("11187")){
                                    activity.mDatas3.add(new FileBean(Integer.parseInt(activity.listRegion.get(i).getFid()),
                                            Integer.parseInt(activity.listRegion.get(i).getParentid()), activity.listRegion.get(i).getName()));
                                }

                                else if (activity.listRegion.get(i).getParentid().equals("11190")){
                                    activity.mDatas3.add(new FileBean(Integer.parseInt(activity.listRegion.get(i).getFid()),
                                            Integer.parseInt(activity.listRegion.get(i).getParentid()), activity.listRegion.get(i).getName()));
                                }

                                else if (activity.listRegion.get(i).getParentid().equals("11205")){
                                    activity.mDatas3.add(new FileBean(Integer.parseInt(activity.listRegion.get(i).getFid()),
                                            Integer.parseInt(activity.listRegion.get(i).getParentid()), activity.listRegion.get(i).getName()));
                                }

                                else if (activity.listRegion.get(i).getParentid().equals("1106515")){
                                    activity.mDatas3.add(new FileBean(Integer.parseInt(activity.listRegion.get(i).getFid()),
                                            Integer.parseInt(activity.listRegion.get(i).getParentid()), activity.listRegion.get(i).getName()));
                                }





                            }


                            try
                            {
                                activity.mAdapter = new SimpleTreeAdapter<FileBean>(activity.mTree, activity, activity.mDatas3, 10);//			mAdapter = new SimpleTreeAdapter<Bean>(mTree, this, mDatas, 10);
                                activity.mAdapter.setOnTreeNodeClickListener(new TreeListViewAdapter.OnTreeNodeClickListener()
                                {
                                    @Override
                                    public void onClick(Node node, int position)
                                    {
                                        if (node.isLeaf())
                                        {
                                            Toast.makeText(activity, node.getName(),
                                                    Toast.LENGTH_SHORT).show();

                                            Intent intent = new Intent(activity, StaffActivity.class);
                                            intent.putExtra("fid", node.getId()+"");
                                            activity.startActivity(intent);

                                        }
                                    }

                                });

                            } catch (Exception e)
                            {
                                e.printStackTrace();
                            }
                            activity.mTree.setAdapter(activity.mAdapter);
                        }else {
                            activity.progressBar.cancel();
                            Toast.makeText(activity, "没有数据", Toast.LENGTH_SHORT).show();
                        }
                        break;

                    case 1:
                        JsonHelper jsonHelper1 = new JsonHelper();
                        activity.listSearch = jsonHelper1.parseContact((String)msg.obj);
                        if (activity.listSearch!=null && activity.listSearch.size()!=0){
                            activity.progressBar.cancel();
                            activity.mStaffAdapter = new StaffAdapter(activity, activity.listSearch);
                            activity.lvSearch.setAdapter(activity.mStaffAdapter);
                            InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
//                          imm.showSoftInput(view,InputMethodManager.SHOW_FORCED);
                            imm.hideSoftInputFromWindow(activity.ivSearch.getWindowToken(), 0); //强制隐藏键盘
                        }else {
                            activity.progressBar.cancel();
                            Toast.makeText(activity, "抱歉，没有数据", Toast.LENGTH_SHORT).show();
                        }
                        break;
                }
            }
        }
    }

    private final MyHandler mHandler = new MyHandler(this);



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tree);
        initViews();
//        initDatas();


        if (Tools.isNetworkAvailable(this)){
            getRegion();
        }else {
            Toast.makeText(this, "当前没有可用的网络", Toast.LENGTH_SHORT).show();
        }


        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                flTitle.setVisibility(View.GONE);
                llSearch.setVisibility(View.VISIBLE);
                mTree.setVisibility(View.GONE);
                lvSearch.setVisibility(View.VISIBLE);

            }
        });

        btnBack2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                flTitle.setVisibility(View.VISIBLE);
                llSearch.setVisibility(View.GONE);
                lvSearch.setVisibility(View.GONE);
                mTree.setVisibility(View.VISIBLE);
                etSearch.getText().clear();
                if (listSearch!=null){
                    listSearch.clear();
                    mStaffAdapter.notifyDataSetChanged();
                    lvSearch.setAdapter(mStaffAdapter);
                }

            }
        });

        ivSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!etSearch.getText().toString().equals("")){
                    if (listSearch!=null && mStaffAdapter!=null){
                        listSearch.clear();
                        mStaffAdapter.notifyDataSetChanged();
                        lvSearch.setAdapter(mStaffAdapter);
                    }
                    if (Tools.isNetworkAvailable(TreeActivity.this)){
                        getSearchResult(etSearch.getText().toString());
//                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
////                      imm.showSoftInput(view,InputMethodManager.SHOW_FORCED);
//                        imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘
                    }else {
                        Toast.makeText(TreeActivity.this, "当前网络不可用", Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Toast.makeText(TreeActivity.this, "请输入姓名或手机号", Toast.LENGTH_SHORT).show();
                }
            }
        });




    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    private void initViews(){
        flTitle = (FrameLayout) findViewById(R.id.flTitle);
        llSearch = (LinearLayout) findViewById(R.id.llSearch);
        btnBack = (Button) findViewById(R.id.btnBack);
        btnBack2 = (Button) findViewById(R.id.btnBack2);
        btnSearch = (Button)findViewById(R.id.btnSearch);
        mTree = (ListView) findViewById(R.id.id_tree);
        lvSearch = (ListView) findViewById(R.id.lvSearch);
        etSearch = (EditText) findViewById(R.id.etSearch);
        ivSearch = (ImageView) findViewById(R.id.ivSearch);
    }


    private void initDatas()
    {


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        progressBar = null;
        if (progressBar != null)
            progressBar.dismiss();
    }

    private void getRegion(){

        progressBar = new ProgressDialog(TreeActivity.this);
        progressBar.setCancelable(false);
        progressBar.setMessage("数据加载中 ...");
        progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressBar.setProgress(0);
        progressBar.setMax(100);
        progressBar.show();

        new Thread(){
            public void run(){

                try {
                    URL url = new URL("http://hr.hrqylm.com/app/hr/Region.aspx");
//                    String content = "";
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);
                    // 设置允许输出
                    conn.setDoOutput(true);
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    OutputStream os = conn.getOutputStream();
//                    os.write(content.getBytes("UTF-8"));
                    os.close();
                    //服务器返回的响应码
                    int code = conn.getResponseCode();
                    if (conn.getResponseCode() == 200){
                        InputStream is = conn.getInputStream();
                        String text = Tools.getTextFromStream(is);
                        System.out.println("------------region---------------" + text);
                        Message msg = new Message();
                        msg.what = 0;
                        msg.obj = text;
                        mHandler.sendMessage(msg);
                    }
                }
//                catch (Exception e) {
//                    Toast.makeText(TreeActivity.this, "服务错误！", Toast.LENGTH_SHORT).show();
//                    e.printStackTrace();
//
//                }
                catch (IOException ConnectTimeoutException){

                }


            }
        }.start();
    }

    private void getSearchResult(final String id){

        progressBar = new ProgressDialog(TreeActivity.this);
        progressBar.setCancelable(false);
        progressBar.setMessage("数据加载中 ...");
        progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressBar.setProgress(0);
        progressBar.setMax(100);
        progressBar.show();

        new Thread(){
            public void run(){

                try {
                    URL url = new URL("http://hr.hrqylm.com/app/hr/Number.aspx?no=1&key=" + id);
//                    String content = "";
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);
                    // 设置允许输出
                    conn.setDoOutput(true);
                    conn.setRequestMethod("GET");
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    OutputStream os = conn.getOutputStream();
//                    os.write(content.getBytes("UTF-8"));
                    os.close();
                    //服务器返回的响应码
                    int code = conn.getResponseCode();
                    if (conn.getResponseCode() == 200){
                        InputStream is = conn.getInputStream();
                        String text = Tools.getTextFromStream(is);
                        System.out.println("---------------------------" + text);
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = text;
                        mHandler.sendMessage(msg);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        }.start();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            Exeit();
            return false;
        }

        return super.onKeyDown(keyCode, event);
    }

    private void Exeit() {

        AlertDialog alertDialog = new AlertDialog.Builder(this).setTitle("提醒")
                .setMessage("是否退出华瑞通讯录")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }

                }).setNegativeButton("取消",

                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).create(); // 创建对话框
        alertDialog.show(); // 显示对话框
    }








}
